<script setup>
import { GetAddBookAPI, GetBookListAPI, GetDeleteBookAPI, GetEditBookAPI, GetToDeleteBookAPI, GetUploadAPI } from '@/apis/book';
import { ElMessage } from 'element-plus';


const bookList = ref()
const getData = async () => {
  const result = await GetBookListAPI()
  bookList.value = result
}


const rules = {
  bookName: {
    required: true, message: '书名不能为空', trigger: 'blur',
  },
  bookMoney: {
    required: true, message: '价格不能为空', trigger: 'blur',
  },
  bookType: {
    required: true, message: '图书描述不能为空', trigger: 'blur',
  },
  avatar: {
    required: true, message: '封面不能为空', trigger: 'blur',
  },
  author: {
    required: true, message: '封面不能为空', trigger: 'blur',
  }
}

const drawerText = ref()
// 弹出层表单
const formData = ref({
  author: '',
  avatar: '',
  bookMoney: '',
  bookName: '',
  bookType: '',
  id: '',
  status: ''
})
// const formData = ref()
const drawer = ref(false)
const drawerStatus = ref(1)
const editFn = (row) => {
  formData.value = { ...row }
  fileList.value = [{ url: row.avatar }]
  drawerStatus.value = 1
  drawerText.value = "修改图书信息"
  drawer.value = true
}
const formRef = ref()

// 图片上传
const fileList = ref([])
// 图片预览
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
const onChange = async (file) => {
  const formDataFile = new FormData()
  formDataFile.append('file', file.raw);
  try {
    const result = await GetUploadAPI(formDataFile)
    ElMessage.success("上传成功")
    formData.value.avatar = result.data.data
  } catch (error) {
    ElMessage.error("上传失败")
  }

}

const limitFn = () => {
  ElMessage.warning('最多上传一张图片')
}

// 提交修改
const submitForm = async () => {
  await formRef.value.validate()

  console.log(formData.value);

  if(drawerStatus.value === 1) {
    try {
      await GetEditBookAPI(formData.value)
      ElMessage.success("修改成功")
      getData()
    } catch (error) {
      ElMessage.error("修改失败,请稍后重试")
    }finally{
      drawer.value = false
    }
  }else if(drawerStatus.value === 2) {
    try {
      const sumitData = {
        avatar: formData.value.avatar,
        bookName: formData.value.bookName,
        author: formData.value.author,
        bookType: formData.value.bookType,
        bookMoney: formData.value.bookMoney,
        status: formData.value.status
      }
      await GetAddBookAPI(sumitData)
      ElMessage.success("添加成功")
      getData()
    } catch (error) {
      ElMessage.error("添加失败,请稍后重试")
    }finally{
      drawer.value = false
    }
  }
}

// 删除图书
const deleteFn = async (id) => {
  try {
    await GetDeleteBookAPI(id, 1)
    ElMessage.success("下架成功")
    getData()
  } catch (error) {
    ElMessage.error("下架失败,请稍后重试")
  }
}

// 删除图书
const deleteBookId = ref()
const toDeleteFn = async (id) => {
  deleteBookId.value = id
  isShow.value = true
}
const confirmFn = async () => {
  try {
    await GetToDeleteBookAPI(deleteBookId.value, 3)
    ElMessage.success("删除成功")
    getData()
  } catch (error) {
    ElMessage.error("删除失败,请稍后重试")
  }finally{
    isShow.value = false
  }
}


// 上架图书
const addFn = async (id) => {
  try {
    await GetDeleteBookAPI(id, 2)
    ElMessage.success("上架成功")
    getData()
  } catch (error) {
    ElMessage.error("上架失败,请稍后重试")
  }
}

// 添加图书
const addBookFn = () => {
  formData.value = {
    author: '',
    avatar: '',
    bookMoney: '',
    bookName: '',
    bookType: '',
    id: '',
    status: ''
  }
  fileList.value = []
  drawerText.value = "添加图书信息"
  drawerStatus.value = 2
  formData.value.status = 2
  drawer.value = true
}

const closeFn = (done) => {
  formData.value = {
    author: '',
    avatar: '',
    bookMoney: '',
    bookName: '',
    bookType: '',
    id: '',
    status: ''
  }
  fileList.value = []
  done()
}

const isShow = ref(false)


const loading = ref(true)
onMounted(async() => {
  await getData()
  loading.value = false
})
</script>

<template>
  <div class="bookPage">
    <el-table :data="bookList" height="550" v-loading="loading" element-loading-text="加载中...">
            <el-table-column prop="id" label="图书id" width="80px"/>
            <el-table-column label="图书封面" >
              <template #default="{row}">
                <div class="img">
                  <img :src="row.avatar" alt="">
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="bookName" label="图书名" />
            <el-table-column prop="author" label="作者" />
            <el-table-column prop="bookType" label="图书描述" />
            <el-table-column prop="bookMoney" label="图书价格" />
            <el-table-column prop="status" label="图书状态" >
              <template #default="{row}">
                <el-tag type="success" v-if="row.status === 1">在售中</el-tag>
                <el-tag type="warning" v-else>已下架</el-tag>
              </template>
            </el-table-column>

            <el-table-column align="center" width="240px">
              <template #header>
                <div class="header">
                  操作
                  <el-button @click="addBookFn" type="primary" style="margin-left: 20px;">添加</el-button>
                </div>
              </template>
              <template #default="{ row }">
                <div v-if="row.status === 1">
                  <!-- <el-button type="danger" round @click="editFn(row)">修改</el-button> -->
                  <el-button type="primary" round @click="deleteFn(row.id)">下架</el-button>
                </div>
                <div v-else>
                  <el-button type="success" round @click="addFn(row.id)">上架</el-button>
                  <el-button type="warning" round @click="editFn(row)">修改</el-button>
                  <el-button type="danger" round @click="toDeleteFn(row.id)">删除</el-button>
                </div>
              </template>
            </el-table-column>
    </el-table>


  <!-- 抽屉 -->
  <el-drawer
    v-model="drawer"
    :title="drawerText"
    direction="rtl"
    size="50%"
    :before-close="closeFn"
  >
      <el-form
        ref="formRef"
        style="max-width: 600px"
        :model="formData"
        label-width="auto"
        class="demo-ruleForm"
        label-position="left"
        :rules="rules"
      >
        <el-form-item
          label="图片"
          prop="avatar"
        >
          <el-upload
            v-model:file-list="fileList"
            limit="1"
            :auto-upload="false"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-exceed="limitFn"
            :on-change="onChange"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="书名"
          prop="bookName"
        >
        <el-input
          v-model="formData.bookName"
          type="text"
          autocomplete="off"
        />
        </el-form-item>
        <el-form-item
          label="作者"
          prop="author"
        >
        <el-input
          v-model="formData.author"
          type="text"
          autocomplete="off"
        />
        </el-form-item>
        <el-form-item
          label="图书描述"
          prop="bookType"
        >
        <el-input
          v-model="formData.bookType"
          type="text"
          autocomplete="off"
        />
        </el-form-item>
        <el-form-item
          label="图书价格"
          prop="bookMoney"
        >
        <el-input
          v-model.number="formData.bookMoney"
          type="number"
          autocomplete="off"
        />
        </el-form-item>
        <el-form-item label="图书状态">
          <el-select
            v-model="formData.status"
            placeholder="请选择图书状态"
          >
            <el-option label="在售中" :value="1" />
            <el-option label="已下架" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">{{ drawerStatus === 1 ? '提交修改' : '立即添加' }}</el-button>
        </el-form-item>
      </el-form>
  </el-drawer>

  <!-- 图片预览 -->
  <el-dialog v-model="dialogVisible" :show-close='false' style="width: 432px;">
    <div class="img2">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </div>
  </el-dialog>

  </div>

  <!-- 删除提示 -->
     <!-- 取消弹出层 -->
  <el-dialog :align-center="true" v-model="isShow" :show-close="true" width="500" center>
    <template #header="{ titleId, titleClass }">
      <div class="my-header">
        <h4 :id="titleId" :class="titleClass">确认删除吗?</h4>
      </div>
    </template>
    <template #footer>
      <el-button type="danger" style="width: 150px;" @click="confirmFn">确认</el-button>
    </template>
  </el-dialog>
</template>


<style lang="scss" scoped>
.bookPage .el-card {
  margin-bottom: 10px;
}
.img {
  width: 70px;
  height: 70px;
}
.img img {
  width: 100%;
  height: 100%;
}

.img2 {
  width: 400px;
  height: 400px;
}
.img2 img {
  width: 100%;
  height: 100%;
}
// .el-upload {
//   display: none;
// }
</style>
